package com.evl.core.util.qrcode;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;

import com.evl.core.util.qr.MatrixToImageWriter;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
  
public class QRCodeUtil {  

    private static Logger log = Logger.getLogger(QRCodeUtil.class);
    
	public static void main(String[] args) throws WriterException, IOException {
		createQr("c","http://aasd.com?id=123", 300, 300, "PNG");
	}
    /**
     * 生成二维码
     * @param url 内容
     * @param width 宽度
     * @param height 高度
     * @param format 后缀类型
     * @throws WriterException
     * @throws IOException
     */
    public static String createQr(String filePath,String url,Integer width,Integer height, String  format){
    	  
        String fileName = UUID.randomUUID().toString() + "."+format;
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();  
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");  
        BitMatrix bitMatrix;
		try {
			bitMatrix = new MultiFormatWriter().encode(url,  
			        BarcodeFormat.QR_CODE, width, height, hints);
			 Path path = FileSystems.getDefault().getPath(filePath, fileName);  
		        
			 MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像  
		} catch (Exception e) {
			log.error("createQr error:"+e.getMessage());
			return "";
		}  

        return fileName;
    	
    }
  
}  